<template>
  <div>
    <el-button type="primary" @click="add">
      <el-icon :size="14">
        <plus />
      </el-icon>
      添加
    </el-button>
    <el-button type="info" plain @click="refresh">
      <el-icon :size="14">
        <refresh />
      </el-icon>
      刷新
    </el-button>
  </div>
  <el-divider />
  <div>
    <el-table :data="users" style="width: 100%" row-key="id" border >
      <el-table-column prop="id" label="编号" sortable width="100"></el-table-column>
      <el-table-column prop="username" label="账号" sortable width="180"></el-table-column>
      <el-table-column prop="role" label="角色" sortable width="180"></el-table-column>
      <!--<el-table-column prop="phone" label="电话号码" width="180"></el-table-column>-->
      <el-table-column label="头像">
        <template #default="scope">
          <el-image :src="scope.row.avatar" style="width: 30px"></el-image>
        </template>
      </el-table-column>
      <!--<el-table-column prop="email" label="邮箱"></el-table-column>-->
      <!--<el-table-column prop="city" label="城市"></el-table-column>-->
      <el-table-column prop="lastLogin" label="最后登录时间"></el-table-column>
      <!--<el-table-column prop="statu" label="状态"></el-table-column>-->
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button type="primary" plain size="small" @click="edit(scope.row)">编辑</el-button>
          <el-button type="warning" plain size="small" @click="resetPwd(scope.row.id)">重置密码</el-button>
          <el-button type="danger" plain size="small" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <!--分页-->
      <el-pagination layout="prev, pager, next"
                     :page-size="page.size"
                     @current-change="getUsers"
                     v-model:current-page="page.current"
                     :total="page.total">
      </el-pagination>
    </div>
  </div>
  <!--编辑用户信息-->
  <el-dialog title="编辑角色信息" v-model="dialogVisible" width="30%" @opened="resetForm">
    <div>
      <!--用户信息表单-->
      <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="100px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="userInfo.roleId" placeholder="请选择角色" @change="changeRole">
            <el-option v-for="role in roles" :key="role.code" :label="role.name" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="userInfo.avatar"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-input v-model="userInfo.city"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import {
  addUser,
  editUser,
  userRole,
  userDelete,
  userList,
  userSave,
  resetPassword,
  setUserRole,
  refreshUser
} from "../../api/user";
import {roleList} from "../../api/role";
import {Plus} from "@element-plus/icons-vue";

export default {
  name: 'Users',
  components: {Plus},
  setup() {
    const newUser = {
      username: '',
      avatar: '',
      email: '',
      city: '',
      roleId: ''
    }

    return {
      newUser
    }
  },
  data() {
    return {
      users: [],
      page: {
        total: 0,
        size: 10,
        current: 1
      },
      dialogVisible: false,
      userInfo: this.newUser,
      roles: [],
      rules: {
        username: [{required: true, message: '请输入账号', trigger: 'blur'}],
        avatar: [{required: true, message: '请输入头像地址', trigger: 'blur'}],
        email: [{required: true, message: '请输入邮箱', trigger: 'blur'}, { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}],
        city: [{required: true, message: '请输入城市', trigger: 'blur'}],
        roleId: [{required: true, message: '请选择角色', trigger: 'change'}]
      }
    }
  },
  created() {
    this.getUsers()
    this.getRoles()
  },
  methods: {
    // 获取角色列表
    getUsers() {
      userList(this.page.current, this.page.size).then(res => {
          this.page.total = res.data.total
          this.page.current = res.data.current
          this.page.size = res.data.size
          this.users = res.data.users
      })
    },
    // 获取角色列表
    getRoles() {
      roleList().then(res => {
        this.roles = res.data
      })
    },
    // 添加用户
    add() {
      addUser().then(res => {
        this.userInfo = JSON.parse(JSON.stringify(this.newUser))
        this.dialogVisible = true
      })
    },
    refresh() {
      refreshUser().then(res => {
        this.getUsers()
        ElMessage.success("刷新用户成功")
      })
    },
    // 编辑用户
    edit(row) {
      this.userInfo = JSON.parse(JSON.stringify(row))
      // 判断用户是否有编辑权限
      editUser(row.id).then(res => {
        // 获取用户角色信息
        userRole(row.id).then(res => {
          this.userInfo.roleId = res.data.roleId
          this.dialogVisible = true
        })
      })
    },
    // 保存用户信息
    save() {
      // 校验规则
      this.$refs['userForm'].validate((valid) => {
        if(valid) {
          // 提示
          ElMessageBox.confirm('你正在保存用户信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            userSave(this.userInfo).then(res => {
              ElMessage.success({
                message: res.msg,
                type: 'success'
              })
              this.dialogVisible = false
              this.getUsers() // 刷新用户列表
            })
          }).catch(() => {
            ElMessage.info({
              message: '取消保存',
              type: 'info'
            })
          })
        }
      })
    },
    // 删除用户
    del(id) {
      ElMessageBox.confirm('确认删除用户信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        userDelete(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除用户成功!',
          })
          this.getUsers() // 刷新用户列表
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除',
        })
      })
    },
    // 重置密码
    resetPwd(id) {
      ElMessageBox.confirm('你正在重置用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        resetPassword(id).then(res => {
          ElMessage.success(res.msg)
        })
      }).catch(() => {
        ElMessage.info('取消重置密码')
      })
    },
    // 修改角色
    changeRole(){
      let {id, roleId} = this.userInfo
      setUserRole(id, roleId).then(res => {
        ElMessage.success(res.msg)
      })
    },
    resetForm() {
      this.$refs['userForm'].clearValidate()  // 清空验证信息
    }
  }
}
</script>

<style>

</style>